package com.imstlife.vending.utils;

import android.os.Build;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class RootShellCmd {

	public static void install(String fileName, String packageName) {
		exec3("pm install -r " + fileName,
				"am start -n com.imstlife.vending/.activity.SplashActivity");
	}
	public static void exec3(String... cmds) {

		StringBuffer command = new StringBuffer();
		if (cmds.length <= 0) {
			return;
		}
		for (String cmd : cmds) {
			command.append(cmd).append("\n");
		}

		Process process = null;
		DataOutputStream os = null;

		try {
			//静默安装需要root权限
			process = Runtime.getRuntime().exec("su");
			//			process = Runtime.getRuntime().exec("system/bin/su");
			os = new DataOutputStream(process.getOutputStream());
			os.write(command.toString().getBytes());
			os.writeBytes("exit\n");
			os.flush();
			//执行命令
			process.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			process.destroy();
		}
	}

	private OutputStream os;

	/**
	 * 执行shell指令
	 * 
	 * @param cmd
	 *            指令
	 */
	public final void exec(String cmd) {
		try {
			if (os == null) {
				os = Runtime.getRuntime().exec("su").getOutputStream();
			}
			os.write(cmd.getBytes());
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 后台模拟全局按键
	 * 
	 * @param keyCode
	 *            键值
	 */
	public final void simulateKey(int keyCode) {
		exec("input keyevent " + keyCode + "\n");
	}

	public static void closeBar() {

		if(DeviceUtil.getDeviceType()==DeviceUtil.RK3128){//据说3128隐藏导航栏黑屏
			return;
		}

		try {
			// REQUIRES ROOT
			Build.VERSION_CODES vc = new Build.VERSION_CODES();
			Build.VERSION vr = new Build.VERSION();
			String ProcID = "79"; // HONEYCOMB AND OLDER

			// v.RELEASE //4.0.3
			if (vr.SDK_INT >= vc.ICE_CREAM_SANDWICH) {
				ProcID = "42"; // ICS AND NEWER
			}

			// REQUIRES ROOT
			Log.d("TAG", new String[] {
					"su",
					"-c",
					"service call activity " + ProcID
							+ " s16 com.android.systemui" }
					+ "");
			Process proc = Runtime.getRuntime().exec(
					new String[] {
							"su",
							"-c",
							"service call activity " + ProcID
									+ " s16 com.android.systemui" }); // WAS 79
			proc.waitFor();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}